﻿//  Copyright © 2009-2010 by Rhy A. Mednick
//  All rights reserved.
//  http://rhyduino.codeplex.com
//  
//  Redistribution and use in source and binary forms, with or without modification, 
//  are permitted provided that the following conditions are met:
//  
//  * Redistributions of source code must retain the above copyright notice, this list 
//    of conditions and the following disclaimer.
//  
//  * Redistributions in binary form must reproduce the above copyright notice, this 
//    list of conditions and the following disclaimer in the documentation and/or other 
//    materials provided with the distribution.
//  
//  * Neither the name of Rhy A. Mednick nor the names of its contributors may be used 
//    to endorse or promote products derived from this software without specific prior 
//    written permission.
//  
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
//  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
//  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 
//  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
//  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
//  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
//  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 
//  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
//  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
//  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;

namespace Rhyduino.Charlieplex
{
    public class CharlieplexedArduino : IDisposable
    {
        #region Propertie(s)

        public List<LedDescriptor> LedList
        {
            get { return new List<LedDescriptor>(_ledList); }
        }

        public bool IsLedListInitialized
        {
            get { return _ledList.Length > 0; }
        }

        #endregion

        #region Constructor(s)

        public CharlieplexedArduino(LedDescriptor[] ledDescriptors)
        {
            if (ledDescriptors == null)
            {
                throw new ArgumentNullException("ledDescriptors");
            }
            _arduino = new Arduino("");
            _ledList = ledDescriptors;
            InitializePinList();
        }

        public CharlieplexedArduino(LedDescriptor[] ledDescriptors, string comPortName, int baudRate = 57600)
        {
            if (ledDescriptors == null)
            {
                throw new ArgumentNullException("ledDescriptors");
            }

            _arduino = new Arduino(comPortName, baudRate);
            _ledList = ledDescriptors;
            InitializePinList();
        }

        #endregion

        #region Public Methods

        public void ClearLeds()
        {
            foreach (var pin in _pinList)
            {
                _arduino.Post(
                    FirmataEncoder.BuildSetPinModeRequest(pin, PinMode.Output));
            }
            _arduino.Post(FirmataEncoder.BuildDigitalWriteRequest(0, 0));
        }

        public void Connect()
        {
            if (_arduino == null)
            {
                throw new InvalidOperationException("Unable to open connection because Arduino is not initialized.");
            }
            _arduino.Connect();
        }

        public void Disconnect()
        {
            if (_arduino == null)
            {
                throw new InvalidOperationException("Unable to open connection because Arduino is not initialized.");
            }
            _arduino.Disconnect();
        }

        public void TurnLedOn(int ledIndex)
        {
            TurnLedOn(ledIndex, false);
        }

        public void TurnLedOn(int ledIndex, bool autoClear)
        {
            if (autoClear)
            {
                ClearLeds();
            }

            _arduino.Post(
                FirmataEncoder.BuildSetPinModeRequest(LedList[ledIndex].HighPin, PinMode.Output));
            _arduino.Post(
                FirmataEncoder.BuildSetPinModeRequest(LedList[ledIndex].LowPin, PinMode.Input));
            _arduino.Post(FirmataEncoder.BuildDigitalWriteRequest(0, 1 << (LedList[ledIndex].HighPin - 2)));
        }

        #endregion

        #region Private Methods

        private void InitializePinList()
        {
            foreach (var led in _ledList)
            {
                if (!_pinList.Contains(led.HighPin))
                {
                    _pinList.Add(led.HighPin);
                }
                if (!_pinList.Contains(led.LowPin))
                {
                    _pinList.Add(led.LowPin);
                }
            }
        }

        #endregion

        #region Implementation of IDisposable interface

        #region Public Methods

        /// <summary>
        ///   Disposes the object by releasing referenced memory.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion

        #region Private Fields

        private bool _disposed;

        #endregion

        /// <summary>
        ///   Disposes the object by releasing referenced memory.
        /// </summary>
        /// <param name = "disposing" />
        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }
            if (!disposing)
            {
                return;
            }

            if (_arduino != null)
            {
                _arduino.Dispose();
            }
            // Clean up unmanaged resources. Set large fields to null.

            // All done
            _disposed = true;
        }

        /// <summary>
        ///   Disposes the object by releasing referenced memory.
        /// </summary>
        ~CharlieplexedArduino()
        {
            Dispose(false);
        }

        #endregion

        #region Private Fields

        private readonly Arduino _arduino;
        private readonly LedDescriptor[] _ledList;
        private readonly List<int> _pinList = new List<int>();

        #endregion
    }
}